﻿
using DongFangGuoKai.WMS.ApiService;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Domain.QueceModels;
using SqlSugar;

namespace DongFangGuoKai.WMSPlatform.WebApi.Works
{
    public class CallNumberBackgroundService : BackgroundService
    {

        BackManagerOptions options = new BackManagerOptions();
        public CallNumberBackgroundService(Action<BackManagerOptions> options, IServiceProvider serviceProvider)
        {
            options.Invoke(this.options);
            ServiceProvider = serviceProvider;
        }

        public IServiceProvider ServiceProvider { get; }
        public ILogger<CallNumberBackgroundService> Logger { get; set; }


        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // 延迟启动
            await Task.Delay(this.options.CheckTime, stoppingToken);

            Logger = ServiceProvider.GetRequiredService<ILogger<CallNumberBackgroundService>>();
            //判断如果令牌是否取消
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    Logger.LogInformation($"{options.Name}开始检查..........");
                    var context = ServiceProvider.GetRequiredService<ISqlSugarClient>();
                    //待叫号队列

                    var waitDisPlayQueceRecards = context.Queryable<t_QueceRecard>().Where(t => t.DisplayStatus == 1 || t.CallStatus == 1).OrderBy(o => o.Id).ToList();
                    if (waitDisPlayQueceRecards != null && waitDisPlayQueceRecards.Count > 0)
                    {
                        foreach (t_QueceRecard waitQueceItem in waitDisPlayQueceRecards)
                        {
                            string windowCode = waitQueceItem.CounterNo;
                            //找窗口号
                            if (string.IsNullOrEmpty(windowCode))
                            {
                                var shippingOrderDetail = context.Queryable<t_ShippingOrderDetail>().First(t => t.OrderSN == waitQueceItem.BillNO);
                                if (shippingOrderDetail != null)
                                {
                                    var shippingLockCell = context.Queryable<t_ShippingLockCell>().First(t => t.OrderId == shippingOrderDetail.Id);
                                    windowCode = shippingLockCell.WindowCode;
                                    waitQueceItem.DisplayStatus = 1;
                                    waitQueceItem.CounterNo = windowCode;
                                    context.Updateable(waitQueceItem);
                                     
                                }

                            }
                            else
                            {
                                var queceApiService = ServiceProvider.GetRequiredService<QueceSystemService>();

                                string interfaceName = "insertqueue";
                                string number = waitQueceItem.Number == null ? "" : waitQueceItem.Number;
                                string typeId = "1";
                                string status = "";
                                //显示  
                                if (waitQueceItem.DisplayStatus == 1)
                                {
                                    status = "0";
                                    waitQueceItem.DisplayStatus = 2;
                                    waitQueceItem.DisPlayDate = DateTime.Now;
                                    context.Updateable(waitQueceItem);  
                                    AddQueceModel model = new AddQueceModel()
                                    {
                                        bookid = waitQueceItem.BillNO,
                                        counterno = windowCode,
                                        number = number,
                                        serialid = typeId,
                                        status = status,
                                        interfacename = interfaceName
                                    };
                                    var res = queceApiService.AddQuece(model);
                                    Logger.LogInformation("叫号机作业入参：" + model.ToJson() + "出参：" + res.ToJson());
                                }
                                else
                                //叫号
                                if (waitQueceItem.CallStatus == 1)
                                {
                                    status = "1";

                                    waitQueceItem.CallStatus = 2;
                                    waitQueceItem.CallDate = DateTime.Now;
                                    context.Updateable(waitQueceItem);  
                                    AddQueceModel model = new AddQueceModel()
                                    {
                                        bookid = waitQueceItem.BillNO,
                                        counterno = windowCode,
                                        number = number,
                                        serialid = typeId,
                                        status = status,
                                        interfacename = interfaceName
                                    };
                                    var res = queceApiService.AddQuece(model);
                                    Logger.LogInformation("叫号机作业入参：" + model.ToJson() + "出参：" + res.ToJson());
                                }




                            }

                        }
                    }
                }
                catch (Exception ex)
                {

                    Logger.LogError(this.options.Name + "异常" + ex.Message);
                }


                await Task.Delay(options.CheckTime, stoppingToken);
            }
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine($"{this.options.Name}由于进程退出，正在执行清理工作");

            return base.StopAsync(cancellationToken);
        }


    }
}
